#!/usr/bin/python
# -*- coding: utf-8 -*-
# @name             : 初始化用例模板
# @author           : OneYoung
# @create           : 2024/02/04
# @version          : v1.0
# @desc             : 按模板自动生成对应的用例文件

import os.path
from application.settings import BASE_DIR, CASE_DIR
from utils.get_time import str_date


class CreateCase:
    SCRIPT_DIR = os.path.join(BASE_DIR, 'scripts', 'create_case')

    def __init__(self, path: str):
        """
        :param path: object 路径
        """
        self.object_path = os.path.join(CASE_DIR, path)
        self.path = path

    def run(self):
        """
        自动创建初始化测试路径，如果该路径已经存在，则不执行
        """
        if self.exist(self.object_path):
            print(f"{self.object_path}已经存在,请删除后,重新执行.")
            return False
        print("开始生成用例目录:", self.path)
        self.create_pag(os.path.join(CASE_DIR, self.path))
        self.generate_file("test_case.py")
        print("用例目录生成结束:", self.object_path)

    def create_pag(self, path: str) -> None:
        """
        创建 python 包

        :param path: 绝对路径
        """
        if self.exist(path):
            return
        os.makedirs(path)
        with open(os.path.join(path, "__init__.py"), "w", encoding='utf-8') as f:
            f.write('')

    def generate_file(self, name: str) -> None:
        """
        创建文件
        """
        params = {
            "create_date": str_date(),
        }
        self.create_file(os.path.join(self.object_path, name), name, **params)

    def create_file(self, filepath: str, name: str, **kwargs):
        """
        创建文件
        """
        with open(filepath, "w", encoding="utf-8") as f:
            content = self.__get_template(name)
            f.write(content.format(**kwargs))

    @classmethod
    def exist(cls, path) -> bool:
        """
        判断路径是否已经存在
        """
        return os.path.exists(path)

    def __get_template(self, name: str) -> str:
        """
        获取模板内容
        """
        template = open(os.path.join(self.SCRIPT_DIR, "template", name), "r", encoding="utf-8")
        content = template.read()
        template.close()
        return content
